<template>
  <a-modal
    title="用户操作"
    :mask-closable="false"
    :centered="true"
    v-model="visible"
    :okButtonProps="{ props: { disabled: isDisabled } }"
    @ok="handleSubmit">
    <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" @submit="handleSubmit" >
      <a-form-item style="display:none" >
        <a-input v-decorator="['userId']"/>
      </a-form-item>
      <a-form-item style="display:none" >
        <a-input v-decorator="['unitId']"/>
      </a-form-item>
      <a-form-item style="display:none" >
        <a-input v-decorator="['avatar']"/>
      </a-form-item>
      <a-form-item style="display:none" >
        <a-input v-decorator="['status']"/>
      </a-form-item>
      <a-form-item style="display:none" >
       <a-input v-decorator="['createTime']"/>
      </a-form-item>
      <a-form-item style="display:none" >
        <a-input v-decorator="['createUserId']"/>
      </a-form-item>
      <a-form-item style="display:none" >
        <a-input v-decorator="['userType']"/>
      </a-form-item>
      <a-form-item
        label="所属单位"
      >
        <a-input autocomplete="off" disabled="disabled" v-decorator="['unitName']" />
      </a-form-item>
      <a-form-item
        label="用户名称"
      >
        <a-input autocomplete="off" v-decorator="['userName',{ rules: [{ required: true,message: '请输入用户名称' },{max:20,message: '不能超过20个字符！'}] }]" />
      </a-form-item>
      <a-form-item
        label="登录账号"
      >
        <a-input autocomplete="off" v-decorator="['logName',{ rules: [{ required: true,message: '请输入登录账号' },{max:20,message: '不能超过20个字符！'}] }]" />
      </a-form-item>
      <a-form-item
        label="登录密码"
      >
        <a-input autocomplete="off" v-decorator="['password',{ rules: [{ required: true,message: '请输入密码' },{max:20,message: '不能超过20个字符！'}] }]" />
      </a-form-item>
      <a-form-item
        label="描述">
        <a-textarea autocomplete="off" v-decorator="['describe',{rules:[{max:50,message:'不超过50个字符！'}]}]" auto-size />
      </a-form-item>
      <a-form-item
        label="上传头像">
        <a-upload
          name="file"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :before-upload="beforeUpload"
          :customRequest="customRequest"
          @change="handleChange"
        >
          <img v-if="imageUrl" class="avatar" :src="imageUrl" alt="avatar" />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">
              Upload
            </div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
  import {axios} from '../../utils/request'
  import pick from 'lodash.pick'

  function getBase64(img, callback) {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }
    export default {
        name: 'UserModal',
        data(){
            return {
              formLayout:'vertical',
              visible: false,
              isDisabled: false,
              labelCol: { span: 6 },
              wrapperCol: { span: 10 },
              form: this.$form.createForm(this),
              loading: false,
              imageUrl: '',
              avatar:''
            }
        },
      methods:{
          add(item){
            this.visible = true
            this.isDisabled = false
            this.imageUrl='/avatar.png'
            this.form.resetFields()
            this.$nextTick(() => {
              this.form.setFieldsValue({
                'unitId': item.key,
                'unitName': item.title
              })
            })
          },
        edit(record){
          this.visible = true
          this.isDisabled = false
          this.imageUrl=(record.avatar==null || record.avatar=='')?'/avatar.png':'/api/'+record.avatar
          console.log(this.imageUrl)
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(record, 'userId', 'userName','unitName', 'unitId',
                                     'logName','password','status','describe','avatar',
                                     'createTime','createUserId','userType'
                                     ))
          })
        },
        handleSubmit(e){
          this.form.validateFields((err, values) => {
            if (!err) {
                axios.post(values.userId>0?'/user/update':'user/add',values)
                 .then(response=>{
                  if(response.code==200){
                    this.isDisabled = false
                    this.$emit('ok')
                    this.visible = false
                  }else{
                    this.$message.error(response.message)
                  }
                })
            }else{
              this.$message.error('页面提交错误，刷新页面重新提交！')
              this.isDisabled = true
            }
          })
        },
        customRequest (data) {
            const formData = new FormData()
            formData.append('file', data.file)
            axios.post('/file/upload',formData).then(response=>{
                  const result = response.result
                  if(response.code==200){
                    this.avatar = result.savePath
                     this.$nextTick(() => {
                      this.form.setFieldsValue({
                        avatar: result.savePath
                      })
                       getBase64(data.file, imageUrl => {
                         this.imageUrl = imageUrl
                         this.loading = false
                       })
                    })
                  }else{
                    this.$message.error(result.message)
                  }
            })

        },
        handleChange(info) {
          if (info.file.status === 'uploading') {
            this.loading = true
            return
          }
        },
        beforeUpload(file) {
          const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
          if (!isJpgOrPng) {
            this.$message.error('图片格式不支持!')
          }
          const isLt2M = file.size / 1024 / 1024 < 2
          if (!isLt2M) {
            this.$message.error('图片大小不超过2M!')
          }
          return isJpgOrPng && isLt2M
        }
      }

    }
</script>

<style scoped>
  .avatar{
    width: 100px;
    height: 100px;
  }
  .avatar-uploader > .ant-upload {
    width: 100px;
    height: 100px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>